import json

from django.contrib import messages
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import render, get_object_or_404, redirect
from django.db.models import Count, Q, Avg
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST, require_http_methods
from django.utils import timezone

from user.models import User, UserFollow, PrivateMessage
from .models import Activity, ActivityCategory, ActivityParticipation, ActivityReview, ReviewLike, \
    ReviewReply, BrowsingHistory, ActivityDiscussion, DiscussionShare, DiscussionFavorite, DiscussionLike, \
    DiscussionComment, DiscussionImage, UserRelationship


def get_user_avatar_url(user):
    """
    统一获取用户头像URL的辅助函数
    优先从 User.avatar 获取，其次从 UserProfile.avatar 获取
    """
    if user.avatar:
        return user.avatar.url
    elif hasattr(user, 'profile') and user.profile.avatar:
        return user.profile.avatar.url
    return None

def index(request):
    # 获取搜索参数
    search_query = request.GET.get('search', '')

    # 获取所有活跃的分类
    categories = ActivityCategory.objects.filter(is_active=True)

    # 基础查询集 - 已发布且未开始的活动
    activities = Activity.objects.filter(
        status='published',
        start_time__gte=timezone.now()
    ).select_related('category', 'organizer')

    # 如果有搜索词，过滤活动
    if search_query:
        activities = activities.filter(
            Q(title__icontains=search_query) |
            Q(description__icontains=search_query) |
            Q(location_name__icontains=search_query) |
            Q(address__icontains=search_query) |
            Q(category__name__icontains=search_query) |
            Q(organizer__username__icontains=search_query) |
            Q(highlights__icontains=search_query) |
            Q(notes__icontains=search_query)
        )
        # 搜索时，推荐活动就是搜索结果
        recommended_activities = activities.order_by('-created_at')[:6]
        # 附近活动也是搜索结果
        nearby_activities = activities.order_by('?')[:4]

        # 更新页面标题
        page_title = f'搜索 "{search_query}" 的结果'
    else:
        # 没有搜索时，显示正常的推荐活动
        recommended_activities = activities.order_by('-created_at')[:6]
        # 附近活动
        nearby_activities = activities.order_by('?')[:4]
        page_title = '推荐活动'

    # 获取热门活动（参与人数最多的）
    popular_activities = Activity.objects.filter(
        status='published'
    ).select_related('category').order_by('-current_participants')[:4]

    context = {
        'recommended_activities': recommended_activities,
        'nearby_activities': nearby_activities,
        'categories': categories,
        'popular_activities': popular_activities,
        'search_query': search_query,
        'page_title': page_title,
        'is_search': bool(search_query),  # 标记是否为搜索状态
    }

    return render(request, 'index.html', context)


def activities(request):
    # 获取查询参数
    category_id = request.GET.get('category')
    search_query = request.GET.get('search', '')
    sort_by = request.GET.get('sort', 'newest')
    location_filter = request.GET.get('location')
    status_filter = request.GET.get('status')  # 新增：状态筛选

    # 基础查询集
    activities = Activity.objects.filter(status='published').select_related('category', 'organizer')

    # 分类筛选
    if category_id:
        activities = activities.filter(category_id=category_id)

    # 搜索功能 - 增强模糊搜索
    if search_query:
        activities = activities.filter(
            Q(title__icontains=search_query) |
            Q(description__icontains=search_query) |
            Q(location_name__icontains=search_query) |
            Q(address__icontains=search_query) |
            Q(category__name__icontains=search_query) |
            Q(organizer__username__icontains=search_query) |
            Q(highlights__icontains=search_query) |
            Q(notes__icontains=search_query)
        )

    # 位置筛选
    if location_filter:
        activities = activities.filter(location_name__icontains=location_filter)

    # 新增：状态筛选 - 基于时间状态
    if status_filter:
        now = timezone.now()
        if status_filter == 'upcoming':
            activities = activities.filter(start_time__gt=now)
        elif status_filter == 'ongoing':
            activities = activities.filter(
                start_time__lte=now,
                end_time__gte=now
            )
        elif status_filter == 'ended':
            activities = activities.filter(end_time__lt=now)

    # 如果是AJAX请求，返回JSON格式（用于搜索建议）
    if request.GET.get('format') == 'json':
        activities_list = list(activities.values(
            'id',
            'title',
            'category__name',
            'location_name'
        )[:5])
        # 重命名字段以匹配前端期望的格式
        for activity in activities_list:
            activity['category_name'] = activity.pop('category__name')
        return JsonResponse({'activities': activities_list})

    # 排序
    if sort_by == 'popular':
        activities = activities.order_by('-current_participants')
    elif sort_by == 'soonest':
        activities = activities.order_by('start_time')
    elif sort_by == 'newest':
        activities = activities.order_by('-created_at')
    elif sort_by == 'most_comments':
        activities = activities.annotate(comment_count=Count('reviews')).order_by('-comment_count')

    # 分页
    paginator = Paginator(activities, 9)  # 每页9个活动
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    # 获取所有分类
    categories = ActivityCategory.objects.filter(is_active=True)

    # 热门活动（基于参与人数）
    popular_activities = Activity.objects.filter(
        status='published'
    ).select_related('category').order_by('-current_participants')[:4]

    context = {
        'page_obj': page_obj,
        'categories': categories,
        'popular_activities': popular_activities,
        'selected_category': category_id,
        'search_query': search_query,
        'sort_by': sort_by,
        'location_filter': location_filter or '',
        'status_filter': status_filter or '',  # 新增：传递状态筛选值
        'total_activities': activities.count(),
    }

    return render(request, 'active.html', context)


def active_detail(request, activity_id):
    try:
        # 获取活动，不限制状态，并预加载相关数据
        activity = Activity.objects.select_related(
            'category',
            'organizer',
            'organizer__profile'
        ).prefetch_related(
            'participants__user__profile'
        ).get(id=activity_id)

        # 权限检查：非发布状态的活动只有组织者和管理员可以查看
        if activity.status != 'published':
            if not request.user.is_authenticated or (request.user != activity.organizer and not request.user.is_staff):
                return render(request, '404.html', {'message': '活动不存在或未发布'}, status=404)

        # 增加浏览数（只有已发布的活动才计数）
        if activity.status == 'published':
            activity.views += 1
            activity.save()

        # 如果用户已登录，记录浏览历史
        if request.user.is_authenticated:
            BrowsingHistory.objects.update_or_create(
                user=request.user,
                activity=activity,
                defaults={'viewed_at': timezone.now()}
            )

        # 获取相关活动（只显示已发布的活动）
        related_activities = Activity.objects.filter(
            category=activity.category,
            status='published'
        ).exclude(id=activity_id).order_by('-created_at')[:3]

        # 获取活动评论
        reviews = activity.reviews.select_related(
            'user',
            'user__profile'
        ).prefetch_related(
            'likes',
            'replies',
            'replies__user',
            'replies__user__profile',
            'replies__likes'
        ).order_by('-created_at')

        # 计算平均评分
        avg_rating = reviews.aggregate(Avg('rating'))['rating__avg'] or 0
        avg_rating = round(avg_rating, 1)

        # 检查用户是否已报名
        user_joined = False
        user_participation = None
        if request.user.is_authenticated:
            user_joined = ActivityParticipation.objects.filter(
                user=request.user,
                activity=activity,
                status__in=['registered', 'attended']
            ).exists()

        # 检查用户是否已评分
        user_reviewed = False
        user_review = None
        if request.user.is_authenticated:
            user_reviewed = ActivityReview.objects.filter(
                user=request.user,
                activity=activity
            ).exists()
            if user_reviewed:
                user_review = ActivityReview.objects.filter(
                    user=request.user,
                    activity=activity
                ).first()

        # 检查是否关注了组织者
        is_following = False
        if request.user.is_authenticated and request.user != activity.organizer:
            is_following = UserFollow.objects.filter(
                follower=request.user,
                following=activity.organizer
            ).exists()

        context = {
            'activity': activity,
            'related_activities': related_activities,
            'reviews': reviews,
            'avg_rating': avg_rating,
            'review_count': reviews.count(),
            'user_joined': user_joined,
            'user_reviewed': user_reviewed,
            'user_review': user_review,
            'is_following': is_following,
            # 时间状态信息也会通过activity对象传递
        }

        return render(request, 'active_detail.html', context)

    except Activity.DoesNotExist:
        return render(request, '404.html', {'message': '活动不存在'}, status=404)


# 活动报名
@login_required
def join_activity(request, activity_id):
    """报名或取消报名活动"""
    if request.method == 'POST':
        try:
            activity = Activity.objects.get(id=activity_id, status='published')

            # 检查用户是否是活动组织者
            if request.user == activity.organizer:
                return JsonResponse({
                    'success': False,
                    'message': '您是活动发起者，无法取消报名'
                })

            # 检查是否已报名
            existing_participation = ActivityParticipation.objects.filter(
                user=request.user,
                activity=activity
            ).first()

            if existing_participation:
                if existing_participation.status in ['registered', 'attended']:
                    # 取消报名
                    existing_participation.status = 'cancelled'
                    existing_participation.save()
                    # 确保参与人数不会变成负数
                    if activity.current_participants > 0:
                        activity.current_participants -= 1
                    activity.save()
                    return JsonResponse({
                        'success': True,
                        'joined': False,
                        'message': '已取消报名'
                    })
                elif existing_participation.status == 'cancelled':
                    # 重新报名
                    # 检查是否已满员
                    if activity.is_full():
                        return JsonResponse({
                            'success': False,
                            'message': '活动已满员'
                        })

                    existing_participation.status = 'registered'
                    existing_participation.save()
                    activity.current_participants += 1
                    activity.save()
                    return JsonResponse({
                        'success': True,
                        'joined': True,
                        'message': '报名成功！'
                    })
            else:
                # 检查是否已满员
                if activity.is_full():
                    return JsonResponse({
                        'success': False,
                        'message': '活动已满员'
                    })

                # 创建报名记录
                ActivityParticipation.objects.create(
                    user=request.user,
                    activity=activity,
                    status='registered'
                )

                # 更新参与人数
                activity.current_participants += 1
                activity.save()

                return JsonResponse({
                    'success': True,
                    'joined': True,
                    'message': '报名成功！'
                })

        except Activity.DoesNotExist:
            return JsonResponse({'success': False, 'message': '活动不存在'})
        except Exception as e:
            return JsonResponse({'success': False, 'message': f'操作失败: {str(e)}'})

    return JsonResponse({'success': False, 'message': '无效请求'})


@require_POST
@csrf_exempt
def add_review(request, activity_id):
    """添加评论 - 整合版本，包含积分奖励"""
    try:
        activity = get_object_or_404(Activity, id=activity_id, status='published')

        if not request.user.is_authenticated:
            return JsonResponse({'success': False, 'message': '请先登录'})

        # 检查用户是否参与过活动
        user_participated = ActivityParticipation.objects.filter(
            user=request.user,
            activity=activity,
            status__in=['registered', 'attended']
        ).exists()

        if not user_participated:
            return JsonResponse({'success': False, 'message': '只有参与过活动的用户才能发表评价'})

        # 解析JSON数据或表单数据
        if request.content_type == 'application/json':
            data = json.loads(request.body)
            rating = int(data.get('rating', 5))
            comment = data.get('comment', '').strip()
            parent_id = data.get('parent_id')
        else:
            rating = int(request.POST.get('rating', 5))
            comment = request.POST.get('comment', '').strip()
            parent_id = request.POST.get('parent_id')

        if not comment:
            return JsonResponse({'success': False, 'message': '评论内容不能为空'})

        if rating < 1 or rating > 5:
            return JsonResponse({'success': False, 'message': '评分必须在1-5之间'})

        # 检查是否是回复评论
        parent_review = None
        if parent_id:
            try:
                parent_review = ActivityReview.objects.get(id=parent_id)
                # 对于回复评论，使用 ReviewReply 模型
                # 检查是否已经回复过
                existing_reply = ReviewReply.objects.filter(
                    review=parent_review,
                    user=request.user
                ).exists()

                if existing_reply:
                    return JsonResponse({'success': False, 'message': '您已经回复过这条评论了'})

                reply = ReviewReply.objects.create(
                    review=parent_review,
                    user=request.user,
                    content=comment
                )

                # 积分奖励：回复评论
                points_earned = award_points(
                    user=request.user,
                    rule_code='reply_review',
                    activity=activity
                )

                # 构建返回数据 - 使用统一的头像获取函数
                reply_data = {
                    'id': reply.id,
                    'username': request.user.username,
                    'user_avatar': get_user_avatar_url(request.user),
                    'comment': comment,
                    'created_at': reply.created_at.strftime('%Y-%m-%d %H:%M'),
                    'is_author': True,
                    'likes_count': 0,
                    'points_earned': points_earned
                }

                return JsonResponse({
                    'success': True,
                    'message': f'回复提交成功{"，获得" + str(points_earned) + "积分" if points_earned else ""}',
                    'review': reply_data,
                    'is_reply': True,
                    'points_earned': points_earned
                })

            except ActivityReview.DoesNotExist:
                return JsonResponse({'success': False, 'message': '父评论不存在'})

        # 检查用户是否已经评价过这个活动（主评论）
        existing_review = ActivityReview.objects.filter(
            user=request.user,
            activity=activity
        ).first()

        if existing_review:
            return JsonResponse({
                'success': False,
                'message': '您已经对该活动发表过评价了'
            })

        # 创建主评论（只有主评论需要评分）
        review = ActivityReview.objects.create(
            user=request.user,
            activity=activity,
            rating=rating,
            comment=comment,
            is_verified=True
        )

        # 积分奖励：发表评价
        points_earned = award_points(
            user=request.user,
            rule_code='publish_review',
            activity=activity
        )

        # 计算新的平均评分
        avg_rating = activity.reviews.aggregate(avg=Avg('rating'))['avg'] or 0
        avg_rating = round(avg_rating, 1)

        # 构建返回数据 - 使用统一的头像获取函数
        review_data = {
            'id': review.id,
            'username': request.user.username,
            'user_avatar': get_user_avatar_url(request.user),
            'rating': rating,
            'comment': comment,
            'created_at': review.created_at.strftime('%Y-%m-%d %H:%M'),
            'is_verified': True,
            'like_count': 0,
            'is_author': True,
            'points_earned': points_earned
        }

        return JsonResponse({
            'success': True,
            'message': f'评价提交成功{"，获得" + str(points_earned) + "积分" if points_earned else ""}',
            'review': review_data,
            'avg_rating': avg_rating,
            'is_reply': False,
            'points_earned': points_earned
        })

    except Exception as e:
        return JsonResponse({'success': False, 'message': f'系统错误: {str(e)}'})


def award_points(user, rule_code, activity=None):
    """
    临时的积分奖励函数
    在实际项目中，您需要连接到您的积分系统
    """
    try:
        # 积分规则映射
        points_rules = {
            'publish_review': 10,  # 发表评价奖励10积分
            'reply_review': 5,  # 回复评论奖励5积分
            'join_activity': 20,  # 参加活动奖励20积分
            'create_activity': 30,  # 创建活动奖励30积分
        }

        points = points_rules.get(rule_code, 0)

        # 这里可以添加实际的积分逻辑
        # 例如更新用户积分、记录积分日志等

        # 临时实现 - 只返回积分值，不实际修改数据库
        print(f"用户 {user.username} 获得 {points} 积分，规则: {rule_code}")

        return points

    except Exception as e:
        print(f"积分奖励错误: {e}")
        return 0

@require_POST
@csrf_exempt
def reply_review(request, review_id):
    """回复评论 - API版本"""
    try:
        parent_review = get_object_or_404(ActivityReview, id=review_id)

        if not request.user.is_authenticated:
            return JsonResponse({'success': False, 'message': '请先登录'})

        # 解析JSON数据
        if request.content_type == 'application/json':
            data = json.loads(request.body)
            content = data.get('content', '').strip()
        else:
            content = request.POST.get('content', '').strip()

        if not content:
            return JsonResponse({'success': False, 'message': '回复内容不能为空'})

        # 创建回复
        reply = ReviewReply.objects.create(
            review=parent_review,
            user=request.user,
            content=content
        )

        # 构建返回数据 - 使用统一的头像获取函数
        reply_data = {
            'id': reply.id,
            'username': request.user.username,
            'user_avatar': get_user_avatar_url(request.user),
            'content': content,
            'created_at': reply.created_at.strftime('%Y-%m-%d %H:%M'),
            'is_author': True,
            'likes_count': 0
        }

        return JsonResponse({
            'success': True,
            'message': '回复提交成功',
            'reply': reply_data
        })

    except Exception as e:
        return JsonResponse({'success': False, 'message': f'系统错误: {str(e)}'})


@require_POST
@login_required
@csrf_exempt
def like_review(request, review_id):
    """点赞/取消点赞评论 - API版本"""
    try:
        review = get_object_or_404(ActivityReview, id=review_id)

        # 检查是否已经点赞
        like_exists = ReviewLike.objects.filter(
            user=request.user,
            review=review
        ).exists()

        if like_exists:
            # 取消点赞
            ReviewLike.objects.filter(user=request.user, review=review).delete()
            liked = False
        else:
            # 添加点赞
            ReviewLike.objects.create(user=request.user, review=review)
            liked = True

        # 获取更新后的点赞数
        like_count = review.likes.count()

        return JsonResponse({
            'success': True,
            'liked': liked,
            'likes_count': like_count
        })

    except Exception as e:
        return JsonResponse({'success': False, 'message': f'系统错误: {str(e)}'})


@require_POST
@login_required
@csrf_exempt
def delete_review(request, review_id):
    """删除评论或回复"""
    try:
        is_reply = request.POST.get('is_reply', 'false').lower() == 'true'
        print(f"尝试删除评论/回复，ID: {review_id}, 用户: {request.user.username}, 是否是回复: {is_reply}")

        if is_reply:
            # 处理回复评论
            try:
                reply = ReviewReply.objects.get(id=review_id)
                print(f"找到回复评论: {reply.id}, 作者: {reply.user.username}")

                # 检查权限：只有回复作者可以删除
                if reply.user != request.user:
                    print(f"权限验证失败: 当前用户 {request.user.username} 不是作者 {reply.user.username}")
                    return JsonResponse({
                        'success': False,
                        'message': '无权删除此回复'
                    })

                # 删除回复
                reply.delete()
                print("回复删除成功")

                return JsonResponse({
                    'success': True,
                    'message': '回复删除成功'
                })

            except ReviewReply.DoesNotExist:
                print(f"未找到ID为 {review_id} 的回复评论")
                return JsonResponse({
                    'success': False,
                    'message': '回复不存在'
                })
        else:
            # 处理主评论
            try:
                review = ActivityReview.objects.get(id=review_id)
                print(f"找到主评论: {review.id}, 作者: {review.user.username}")

                # 检查权限：只有评论作者可以删除
                if review.user != request.user:
                    print(f"权限验证失败: 当前用户 {request.user.username} 不是作者 {review.user.username}")
                    return JsonResponse({
                        'success': False,
                        'message': '无权删除此评论'
                    })

                # 删除评论（这会自动删除相关的回复）
                review.delete()
                print("主评论删除成功")

                return JsonResponse({
                    'success': True,
                    'message': '评论删除成功'
                })

            except ActivityReview.DoesNotExist:
                print(f"未找到ID为 {review_id} 的主评论")
                return JsonResponse({
                    'success': False,
                    'message': '评论不存在'
                })

    except Exception as e:
        print(f"删除过程中发生错误: {str(e)}")
        return JsonResponse({
            'success': False,
            'message': f'删除失败: {str(e)}'
        })


@require_http_methods(["GET"])
@csrf_exempt
def get_activity_reviews(request, activity_id):
    """获取活动的评论列表 - API端点"""
    try:
        activity = get_object_or_404(Activity, id=activity_id, status='published')

        # 获取评论，包含回复和点赞信息
        reviews = activity.reviews.select_related('user').prefetch_related(
            'likes', 'replies', 'replies__user', 'replies__likes'
        ).order_by('-created_at')

        review_list = []
        for review in reviews:
            # 构建评论数据
            review_data = {
                'id': review.id,
                'user': review.user.username,
                'user_avatar': review.user.avatar.url if review.user.avatar else None,
                'rating': review.rating,
                'comment': review.comment,
                'created_at': review.created_at.strftime('%Y-%m-%d %H:%M'),
                'is_verified': review.is_verified,
                'likes_count': review.likes.count(),
                'user_liked': False,
                'is_author': request.user.is_authenticated and review.user == request.user,
                'replies': []
            }

            # 检查当前用户是否点赞
            if request.user.is_authenticated:
                review_data['user_liked'] = ReviewLike.objects.filter(
                    user=request.user, review=review
                ).exists()

            # 构建回复数据
            for reply in review.replies.all():
                reply_data = {
                    'id': reply.id,
                    'user': reply.user.username,
                    'user_avatar': reply.user.avatar.url if reply.user.avatar else None,
                    'comment': reply.content,  # 注意：回复使用 content 字段
                    'created_at': reply.created_at.strftime('%Y-%m-%d %H:%M'),
                    'likes_count': reply.likes.count(),
                    'user_liked': False,
                    'is_author': request.user.is_authenticated and reply.user == request.user
                }

                # 检查当前用户是否点赞回复
                if request.user.is_authenticated:
                    reply_data['user_liked'] = ReviewLike.objects.filter(
                        user=request.user, review=reply
                    ).exists()

                review_data['replies'].append(reply_data)

            review_list.append(review_data)

        return JsonResponse({
            'success': True,
            'reviews': review_list
        })

    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f'获取评论失败: {str(e)}'
        })


# 创建活动
@login_required
def create_activity(request):
    """创建活动视图"""
    if request.method == 'POST':
        try:
            # 获取表单数据
            title = request.POST.get('title', '').strip()
            description = request.POST.get('description', '').strip()
            category_id = request.POST.get('category')
            start_time = request.POST.get('start_time')
            end_time = request.POST.get('end_time')
            location_name = request.POST.get('location_name', '').strip()
            address = request.POST.get('address', '').strip()
            max_participants = request.POST.get('max_participants', 0)

            # 新增：获取经纬度数据
            longitude = request.POST.get('longitude', '').strip()
            latitude = request.POST.get('latitude', '').strip()

            # 处理多行文本字段
            highlights = request.POST.get('highlights', '').strip()
            schedule = request.POST.get('schedule', '').strip()
            notes = request.POST.get('notes', '').strip()

            # 验证必填字段
            if not all([title, description, category_id, start_time, location_name, address]):
                messages.error(request, '请填写所有必填字段')
                return render(request, 'create_activity.html', {
                    'categories': ActivityCategory.objects.filter(is_active=True),
                    'form_data': request.POST
                })

            # 新增：验证经纬度
            if not longitude or not latitude:
                messages.error(request, '请在地图上选择活动地点')
                return render(request, 'create_activity.html', {
                    'categories': ActivityCategory.objects.filter(is_active=True),
                    'form_data': request.POST
                })

            # 验证时间
            start_time_obj = timezone.datetime.fromisoformat(start_time.replace('Z', '+00:00'))
            if end_time:
                end_time_obj = timezone.datetime.fromisoformat(end_time.replace('Z', '+00:00'))
                if end_time_obj <= start_time_obj:
                    messages.error(request, '结束时间必须晚于开始时间')
                    return render(request, 'create_activity.html', {
                        'categories': ActivityCategory.objects.filter(is_active=True),
                        'form_data': request.POST
                    })

            # 验证参与人数
            try:
                max_participants = int(max_participants)
                if max_participants < 1:
                    messages.error(request, '参与人数必须大于0')
                    return render(request, 'create_activity.html', {
                        'categories': ActivityCategory.objects.filter(is_active=True),
                        'form_data': request.POST
                    })
            except ValueError:
                messages.error(request, '参与人数必须是有效数字')
                return render(request, 'create_activity.html', {
                    'categories': ActivityCategory.objects.filter(is_active=True),
                    'form_data': request.POST
                })

            # 新增：转换经纬度为 Float
            try:
                longitude_float = float(longitude)
                latitude_float = float(latitude)
            except ValueError:
                messages.error(request, '经纬度格式错误')
                return render(request, 'create_activity.html', {
                    'categories': ActivityCategory.objects.filter(is_active=True),
                    'form_data': request.POST
                })

            # 获取分类
            category = get_object_or_404(ActivityCategory, id=category_id, is_active=True)

            # 处理图片上传
            image = request.FILES.get('image')
            if not image:
                messages.error(request, '请上传活动图片')
                return render(request, 'create_activity.html', {
                    'categories': ActivityCategory.objects.filter(is_active=True),
                    'form_data': request.POST
                })

            # 创建活动 - 添加经纬度字段
            activity = Activity.objects.create(
                title=title,
                description=description,
                category=category,
                organizer=request.user,
                start_time=start_time_obj,
                end_time=end_time_obj if end_time else None,
                location_name=location_name,
                address=address,
                max_participants=max_participants,
                current_participants=0,  # 初始为0，创建者通过参与记录添加
                image=image,
                highlights=highlights,
                schedule=schedule,
                notes=notes,
                status='pending',
                # 新增：设置经纬度
                longitude=longitude_float,
                latitude=latitude_float
            )

            # 创建者自动参与活动 - 使用 update_or_create 避免重复
            participation, created = ActivityParticipation.objects.update_or_create(
                user=request.user,
                activity=activity,
                defaults={
                    'status': 'registered',
                    'joined_at': timezone.now()
                }
            )

            # 如果创建了新的参与记录，更新参与人数
            if created:
                activity.current_participants += 1
                activity.save()

            messages.success(request, '活动创建成功！')
            return redirect('active_detail', activity_id=activity.id)

        except Exception as e:
            messages.error(request, f'创建活动失败: {str(e)}')
            return render(request, 'create_activity.html', {
                'categories': ActivityCategory.objects.filter(is_active=True),
                'form_data': request.POST
            })

    else:
        # GET 请求，显示创建表单
        categories = ActivityCategory.objects.filter(is_active=True)
        return render(request, 'create_activity.html', {
            'categories': categories
        })


@login_required
def browsing_history(request):
    """浏览历史页面"""
    # 获取用户的浏览历史，按浏览时间倒序排列
    history_records = BrowsingHistory.objects.filter(
        user=request.user
    ).select_related('activity', 'activity__category').order_by('-viewed_at')

    # 分页
    paginator = Paginator(history_records, 10)  # 每页10条记录
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context = {
        'page_obj': page_obj,
        'total_count': history_records.count(),
    }

    return render(request, 'history.html', context)


@require_POST
@login_required
@csrf_exempt
def delete_browsing_history(request, history_id=None):
    """删除浏览历史 - 支持删除单个和清空所有"""
    try:
        if history_id:
            # 删除单个浏览记录
            history_record = get_object_or_404(
                BrowsingHistory,
                id=history_id,
                user=request.user  # 只能删除自己的记录
            )
            history_record.delete()
            message = '删除成功'
        else:
            # 清空所有浏览历史
            deleted_count, _ = BrowsingHistory.objects.filter(user=request.user).delete()
            message = f'已清空所有浏览历史（共{deleted_count}条记录）'

        # 总是返回JSON响应，因为前端使用AJAX
        return JsonResponse({
            'success': True,
            'message': message
        })

    except Exception as e:
        error_message = f'删除失败: {str(e)}'
        return JsonResponse({
            'success': False,
            'message': error_message
        })


@login_required
def add_browsing_history(request, activity_id):
    """添加浏览历史记录（在查看活动详情时调用）"""
    try:
        activity = get_object_or_404(Activity, id=activity_id)

        # 使用 update_or_create 来更新浏览时间或创建新记录
        history_record, created = BrowsingHistory.objects.update_or_create(
            user=request.user,
            activity=activity,
            defaults={'viewed_at': timezone.now()}
        )

        return JsonResponse({
            'success': True,
            'created': created
        })

    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': str(e)
        })


# 社区
def social(request):
    """社区主页 - 显示所有活动的讨论"""
    # 获取搜索参数
    search_query = request.GET.get('search', '')

    # 基础查询集 - 所有讨论，按时间倒序
    discussions = ActivityDiscussion.objects.all().select_related('user', 'activity')

    # 搜索功能
    if search_query:
        discussions = discussions.filter(
            Q(content__icontains=search_query) |
            Q(user__username__icontains=search_query) |
            Q(activity__title__icontains=search_query)
        )

    # 热门讨论（按点赞数排序）
    popular_discussions = ActivityDiscussion.objects.all().order_by('-like_count')[:5]

    # 获取所有已发布的活动（用于发布讨论）
    all_activities = Activity.objects.filter(status='published')

    # 为每个讨论添加当前用户是否点赞和收藏的标志
    for discussion in discussions:
        if request.user.is_authenticated:
            discussion.is_liked = DiscussionLike.objects.filter(user=request.user, discussion=discussion).exists()
            discussion.is_favorited = DiscussionFavorite.objects.filter(user=request.user,
                                                                        discussion=discussion).exists()
        else:
            discussion.is_liked = False
            discussion.is_favorited = False

    # 分页
    paginator = Paginator(discussions, 10)  # 每页10个讨论
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context = {
        'page_obj': page_obj,
        'popular_discussions': popular_discussions,
        'all_activities': all_activities,
        'search_query': search_query,
        'total_discussions': ActivityDiscussion.objects.count(),
        'today_discussions': ActivityDiscussion.objects.filter(created_at__date=timezone.now().date()).count(),
        'total_likes': DiscussionLike.objects.count(),
        'total_comments': DiscussionComment.objects.count(),
        'active_users': User.objects.annotate(
            discussion_count=Count('discussion_posts'),
            like_count=Count('discussion_posts__likes')
        ).order_by('-discussion_count', '-like_count')[:5],
    }

    return render(request, 'social.html', context)


@login_required
@require_POST
def create_discussion(request):
    """创建讨论帖子"""
    try:
        activity_id = request.POST.get('activity')
        activity = get_object_or_404(Activity, id=activity_id, status='published')

        content = request.POST.get('content', '').strip()
        if not content:
            messages.error(request, '讨论内容不能为空')
            return redirect('social')

        # 创建讨论
        discussion = ActivityDiscussion.objects.create(
            activity=activity,
            user=request.user,
            content=content,
        )

        # 处理图片上传
        uploaded_files = request.FILES.getlist('images')
        for image_file in uploaded_files[:5]:  # 限制最多5张
            DiscussionImage.objects.create(
                discussion=discussion,
                image=image_file
            )

        messages.success(request, '讨论发布成功！')
        return redirect('social')

    except Exception as e:
        messages.error(request, f'发布讨论失败: {str(e)}')
        return redirect('social')


def discussion_detail(request, discussion_id):
    """讨论详情页面"""
    discussion = get_object_or_404(
        ActivityDiscussion.objects.select_related('user', 'activity'),
        id=discussion_id
    )

    # 检查当前用户是否已关注帖子作者
    is_following = False
    if request.user.is_authenticated and request.user != discussion.user:
        is_following = UserRelationship.objects.filter(
            follower=request.user,
            following=discussion.user
        ).exists()

    # 获取讨论的评论
    comments = DiscussionComment.objects.filter(
        discussion=discussion
    ).select_related('user').order_by('created_at')

    # 检查用户是否已点赞
    user_liked = False
    if request.user.is_authenticated:
        user_liked = DiscussionLike.objects.filter(
            user=request.user,
            discussion=discussion
        ).exists()

    # 相关讨论（同活动的其他讨论）
    related_discussions = ActivityDiscussion.objects.filter(
        activity=discussion.activity
    ).exclude(id=discussion_id).order_by('-created_at')[:3]

    context = {
        'discussion': discussion,
        'comments': comments,
        'user_liked': user_liked,
        'related_discussions': related_discussions,
        'is_following': is_following,
    }

    return render(request, 'discussion_detail.html', context)


@login_required
@require_POST
def add_discussion_comment(request, discussion_id):
    """添加讨论评论 - 增强版，支持回复"""
    try:
        discussion = get_object_or_404(ActivityDiscussion, id=discussion_id)

        content = request.POST.get('content', '').strip()
        if not content:
            if request.headers.get('x-requested-with') == 'XMLHttpRequest':
                return JsonResponse({'success': False, 'message': '评论内容不能为空'})
            messages.error(request, '评论内容不能为空')
            return redirect('discussion_detail', discussion_id=discussion_id)

        parent_comment_id = request.POST.get('parent_comment_id')
        parent_comment = None
        if parent_comment_id:
            parent_comment = get_object_or_404(DiscussionComment, id=parent_comment_id)

        # 创建评论
        comment = DiscussionComment.objects.create(
            discussion=discussion,
            user=request.user,
            content=content,
            parent_comment=parent_comment
        )

        # 更新评论计数
        discussion.comment_count = DiscussionComment.objects.filter(discussion=discussion).count()
        discussion.save()

        if request.headers.get('x-requested-with') == 'XMLHttpRequest':
            return JsonResponse({
                'success': True,
                'message': '评论成功！',
                'comment_id': comment.id,
                'username': request.user.username,
                'content': content,
                'created_at': comment.created_at.strftime('%Y-%m-%d %H:%M'),
                'is_reply': bool(parent_comment)
            })
        else:
            messages.success(request, '评论成功！')
            return redirect('discussion_detail', discussion_id=discussion_id)

    except Exception as e:
        if request.headers.get('x-requested-with') == 'XMLHttpRequest':
            return JsonResponse({'success': False, 'message': f'评论失败: {str(e)}'})
        else:
            messages.error(request, f'评论失败: {str(e)}')
            return redirect('discussion_detail', discussion_id=discussion_id)


@login_required
@require_POST
def like_discussion(request, discussion_id):
    """点赞/取消点赞讨论"""
    try:
        discussion = get_object_or_404(ActivityDiscussion, id=discussion_id)

        # 检查是否已点赞
        like, created = DiscussionLike.objects.get_or_create(
            user=request.user,
            discussion=discussion
        )

        if not created:
            # 已点赞，执行取消点赞
            like.delete()
            discussion.like_count = DiscussionLike.objects.filter(discussion=discussion).count()
            discussion.save()
            return JsonResponse({
                'success': True,
                'message': '取消点赞',
                'liked': False,
                'like_count': discussion.like_count
            })
        else:
            # 新点赞
            discussion.like_count = DiscussionLike.objects.filter(discussion=discussion).count()
            discussion.save()
            return JsonResponse({
                'success': True,
                'message': '点赞成功',
                'liked': True,
                'like_count': discussion.like_count
            })

    except Exception as e:
        return JsonResponse({'success': False, 'message': f'操作失败: {str(e)}'})


@login_required
@require_POST
def favorite_discussion(request, discussion_id):
    """收藏/取消收藏讨论"""
    try:
        discussion = get_object_or_404(ActivityDiscussion, id=discussion_id)

        # 检查是否已收藏
        favorite, created = DiscussionFavorite.objects.get_or_create(
            user=request.user,
            discussion=discussion
        )

        if not created:
            # 已收藏，执行取消收藏
            favorite.delete()
            return JsonResponse({
                'success': True,
                'message': '取消收藏',
                'favorited': False,
                'favorite_count': DiscussionFavorite.objects.filter(discussion=discussion).count()
            })
        else:
            # 新收藏
            return JsonResponse({
                'success': True,
                'message': '收藏成功',
                'favorited': True,
                'favorite_count': DiscussionFavorite.objects.filter(discussion=discussion).count()
            })

    except Exception as e:
        return JsonResponse({'success': False, 'message': f'操作失败: {str(e)}'})


@login_required
@require_POST
def share_discussion(request, discussion_id):
    """转发讨论"""
    try:
        discussion = get_object_or_404(ActivityDiscussion, id=discussion_id)

        # 创建转发记录
        DiscussionShare.objects.create(
            user=request.user,
            discussion=discussion
        )

        # 更新分享计数
        discussion.shares_count = DiscussionShare.objects.filter(discussion=discussion).count()
        discussion.save()

        return JsonResponse({
            'success': True,
            'message': '转发成功',
            'shares_count': discussion.shares_count
        })

    except Exception as e:
        return JsonResponse({'success': False, 'message': f'转发失败: {str(e)}'})


@login_required
@require_POST
def delete_discussion(request, discussion_id):
    """删除讨论"""
    try:
        discussion = get_object_or_404(ActivityDiscussion, id=discussion_id)

        # 检查用户是否有权限删除（只能是发布者）
        if discussion.user != request.user:
            return JsonResponse({'success': False, 'message': '无权删除此讨论'})

        discussion.delete()
        return JsonResponse({'success': True, 'message': '讨论已删除'})

    except Exception as e:
        return JsonResponse({'success': False, 'message': f'删除失败: {str(e)}'})


@login_required
@require_POST
def add_discussion_detail_comment(request, discussion_id):
    """添加讨论评论 - 确保始终返回JSON"""
    try:
        # 检查用户认证状态
        if not request.user.is_authenticated:
            return JsonResponse({
                'success': False,
                'message': '请先登录',
                'redirect': '/meet/login/'
            }, status=401)

        # 获取讨论对象
        try:
            discussion = ActivityDiscussion.objects.get(id=discussion_id)
        except ActivityDiscussion.DoesNotExist:
            return JsonResponse({
                'success': False,
                'message': '讨论不存在'
            }, status=404)

        # 解析表单数据
        content = request.POST.get('content', '').strip()
        parent_comment_id = request.POST.get('parent_comment_id')

        print(f"收到评论请求: 用户={request.user.username}, 内容长度={len(content)}, 父评论ID={parent_comment_id}")

        if not content:
            return JsonResponse({
                'success': False,
                'message': '评论内容不能为空'
            })

        # 验证内容长度
        if len(content) > 1000:
            return JsonResponse({
                'success': False,
                'message': '评论内容不能超过1000字'
            })

        parent_comment = None
        if parent_comment_id:
            try:
                parent_comment = DiscussionComment.objects.get(id=parent_comment_id, discussion=discussion)
                print(f"找到父评论: {parent_comment.id}")
                # 检查回复层级，限制最多2层
                if parent_comment.parent_comment:
                    return JsonResponse({
                        'success': False,
                        'message': '只能回复到第二层'
                    })
            except DiscussionComment.DoesNotExist:
                return JsonResponse({
                    'success': False,
                    'message': '父评论不存在'
                })

        # 创建评论
        comment = DiscussionComment.objects.create(
            discussion=discussion,
            user=request.user,
            content=content,
            parent_comment=parent_comment
        )
        print(f"评论创建成功: {comment.id}")

        # 更新评论计数
        discussion.comment_count = DiscussionComment.objects.filter(discussion=discussion).count()
        discussion.save()

        # 构建返回数据
        comment_data = {
            'id': comment.id,
            'username': comment.user.username,
            'user_avatar': comment.user.avatar.url if comment.user.avatar else None,
            'content': comment.content,
            'created_at': comment.created_at.strftime('%m月%d日 %H:%M'),
            'likes_count': 0,
            'user_liked': False,
            'is_reply': bool(parent_comment),
            'parent_username': parent_comment.user.username if parent_comment else None,
            'parent_comment_id': parent_comment.id if parent_comment else None
        }

        print(f"返回评论数据: {comment_data}")

        return JsonResponse({
            'success': True,
            'message': '评论成功！',
            'comment': comment_data
        })

    except Exception as e:
        import logging
        import traceback
        logger = logging.getLogger(__name__)
        logger.error(f"评论失败: {str(e)}")
        logger.error(traceback.format_exc())

        print(f"评论失败: {str(e)}")
        print(traceback.format_exc())

        # 确保返回JSON格式的错误信息
        return JsonResponse({
            'success': False,
            'message': f'评论失败: {str(e)}'
        }, status=500)


@login_required
@require_POST
def like_discussion_detail_comment(request, comment_id):
    """点赞/取消点赞讨论评论"""
    try:
        comment = get_object_or_404(DiscussionComment, id=comment_id)

        # 使用 DiscussionLike 模型来模拟评论点赞
        # 在实际项目中，你可能需要创建专门的评论点赞模型
        like, created = DiscussionLike.objects.get_or_create(
            user=request.user,
            discussion=comment.discussion  # 使用讨论来模拟
        )

        if not created:
            # 取消点赞
            like.delete()
            liked = False
        else:
            # 点赞
            liked = True

        # 模拟点赞数 - 使用讨论的点赞数
        like_count = DiscussionLike.objects.filter(discussion=comment.discussion).count()

        return JsonResponse({
            'success': True,
            'liked': liked,
            'likes_count': like_count
        })

    except Exception as e:
        return JsonResponse({'success': False, 'message': f'操作失败: {str(e)}'})


@login_required
@require_POST
def delete_discussion_detail_comment(request, discussion_id):
    """删除讨论评论 - 修复版本"""
    try:
        # 从POST数据中获取comment_id
        comment_id = request.POST.get('comment_id')
        print(f"尝试删除评论，ID: {comment_id}, 用户: {request.user.username}")

        if not comment_id:
            return JsonResponse({'success': False, 'message': '评论ID不能为空'})

        # 获取评论对象 - 简化查询，只根据ID查找
        try:
            comment = DiscussionComment.objects.get(id=comment_id)
            print(f"找到评论: {comment.id}, 作者: {comment.user.username}")
        except DiscussionComment.DoesNotExist:
            print(f"未找到ID为 {comment_id} 的评论")
            return JsonResponse({'success': False, 'message': '评论不存在'})

        # 检查权限：只有评论作者可以删除
        if comment.user != request.user:
            print(f"权限验证失败: 当前用户 {request.user.username} 不是作者 {comment.user.username}")
            return JsonResponse({'success': False, 'message': '无权删除此评论'})

        # 记录评论信息
        deleted_comment_id = comment.id
        is_reply = comment.parent_comment is not None

        # 删除评论
        comment.delete()
        print(f"评论删除成功: {deleted_comment_id}")

        # 更新讨论的评论计数
        try:
            discussion = ActivityDiscussion.objects.get(id=discussion_id)
            discussion.comment_count = DiscussionComment.objects.filter(discussion=discussion).count()
            discussion.save()
            print(f"更新评论计数: {discussion.comment_count}")
        except ActivityDiscussion.DoesNotExist:
            print(f"未找到讨论: {discussion_id}")
            # 即使讨论不存在，也返回成功，因为评论已经删除

        return JsonResponse({
            'success': True,
            'message': '评论删除成功',
            'deleted_comment_id': deleted_comment_id,
            'new_comment_count': discussion.comment_count if 'discussion' in locals() else 0,
            'is_reply': is_reply
        })

    except Exception as e:
        print(f"删除评论过程中发生错误: {str(e)}")
        return JsonResponse({
            'success': False,
            'message': f'删除失败: {str(e)}'
        })


# 获取时间
def check_activity_status(request, activity_id):
    """检查活动状态是否发生变化 - API端点"""
    try:
        activity = get_object_or_404(Activity, id=activity_id)

        # 获取当前计算的状态
        current_status = activity.time_based_status

        # 检查状态是否应该变化
        now = timezone.now()
        should_be_status = 'upcoming'
        if now >= activity.start_time and now <= activity.end_time:
            should_be_status = 'ongoing'
        elif now > activity.end_time:
            should_be_status = 'ended'

        # 检查状态是否发生变化
        status_changed = (current_status != should_be_status and
                          activity.status == 'published' and
                          activity.time_based_status != 'cancelled')

        # 如果状态应该变化但还没更新，返回需要刷新的信号
        if status_changed:
            return JsonResponse({
                'current_status': current_status,
                'should_be_status': should_be_status,
                'status_changed': True,
                'message': f'活动状态已从 {current_status} 变为 {should_be_status}'
            })
        else:
            return JsonResponse({
                'current_status': current_status,
                'should_be_status': should_be_status,
                'status_changed': False,
                'message': '活动状态未发生变化'
            })

    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f'检查状态失败: {str(e)}'
        })


def get_activity_time_status(request, activity_id):
    """获取活动时间状态信息 - 用于前端显示"""
    try:
        activity = get_object_or_404(Activity, id=activity_id)

        now = timezone.now()
        start_time = activity.start_time
        end_time = activity.end_time

        # 计算时间相关信息
        time_info = {
            'current_status': activity.time_based_status,
            'status_display': activity.status_display,
            'start_time': start_time.isoformat(),
            'end_time': end_time.isoformat(),
            'current_time': now.isoformat(),
            'can_join': activity.can_join,
            'is_full': activity.is_full(),
            'available_spots': activity.available_spots()
        }

        # 如果是即将开始的活动，计算倒计时
        if activity.time_based_status == 'upcoming':
            time_until_start = start_time - now
            time_info['countdown'] = {
                'days': time_until_start.days,
                'hours': time_until_start.seconds // 3600,
                'minutes': (time_until_start.seconds % 3600) // 60,
                'seconds': time_until_start.seconds % 60
            }

        # 如果是进行中的活动，计算剩余时间
        elif activity.time_based_status == 'ongoing':
            time_until_end = end_time - now
            time_info['time_remaining'] = {
                'days': time_until_end.days,
                'hours': time_until_end.seconds // 3600,
                'minutes': (time_until_end.seconds % 3600) // 60,
                'seconds': time_until_end.seconds % 60
            }

        return JsonResponse({
            'success': True,
            'time_info': time_info
        })

    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f'获取时间状态失败: {str(e)}'
        })


# 私信
@login_required
@csrf_exempt
def send_message(request):
    """发送私信 - 添加关注限制"""
    if request.method == 'POST':
        try:
            # 从POST数据或JSON数据中获取参数
            if request.content_type == 'application/json':
                data = json.loads(request.body)
                receiver_id = data.get('receiver_id')
                content = data.get('content', '').strip()
            else:
                receiver_id = request.POST.get('receiver_id')
                content = request.POST.get('content', '').strip()

            if not content:
                return JsonResponse({'success': False, 'message': '消息内容不能为空'})

            if not receiver_id:
                return JsonResponse({'success': False, 'message': '接收者不能为空'})

            try:
                receiver = User.objects.get(id=receiver_id)

                # 检查关注关系
                # from .models import Follow  # 假设您有Follow模型

                # 检查是否已关注对方
                is_following = UserFollow.objects.filter(
                    follower=request.user,
                    following=receiver
                ).exists()

                # 检查对方是否关注自己（互关）
                is_followed_back = UserFollow.objects.filter(
                    follower=receiver,
                    following=request.user
                ).exists()

                # 检查已发送的消息数量
                sent_messages_count = PrivateMessage.objects.filter(
                    sender=request.user,
                    receiver=receiver
                ).count()

                # 限制逻辑：未关注只能发1条，已关注但未互关只能发3条，互关无限制
                if not is_following:
                    # 未关注：只能发1条消息
                    if sent_messages_count >= 1:
                        return JsonResponse({
                            'success': False,
                            'message': '您尚未关注对方，只能发送1条消息。请先关注对方。',
                            'limit_reached': True
                        })
                elif is_following and not is_followed_back:
                    # 已关注但未互关：只能发3条消息
                    if sent_messages_count >= 3:
                        return JsonResponse({
                            'success': False,
                            'message': '对方尚未关注您，您最多只能发送3条消息。',
                            'limit_reached': True
                        })

                # 创建私信
                message = PrivateMessage.objects.create(
                    sender=request.user,
                    receiver=receiver,
                    content=content
                )

                # 返回剩余消息数量
                remaining_messages = 0
                if not is_following:
                    remaining_messages = 1 - (sent_messages_count + 1)
                elif is_following and not is_followed_back:
                    remaining_messages = 3 - (sent_messages_count + 1)

                return JsonResponse({
                    'success': True,
                    'message': '发送成功',
                    'message_id': message.id,
                    'remaining_messages': max(0, remaining_messages),
                    'is_following': is_following,
                    'is_followed_back': is_followed_back
                })

            except User.DoesNotExist:
                return JsonResponse({'success': False, 'message': '用户不存在'})

        except Exception as e:
            print(f"发送私信错误: {str(e)}")
            return JsonResponse({'success': False, 'message': f'发送失败: {str(e)}'})

    return JsonResponse({'success': False, 'message': '无效请求'})


@login_required
@csrf_exempt
def get_messages(request):
    """获取私信 - 整合版本"""
    try:
        user_id = request.GET.get('user_id')
        if not user_id:
            return JsonResponse({'success': False, 'message': '用户ID不能为空'})

        other_user = User.objects.get(id=user_id)

        # 获取双方的消息，按时间排序
        messages = PrivateMessage.objects.filter(
            (Q(sender=request.user) & Q(receiver=other_user)) |
            (Q(sender=other_user) & Q(receiver=request.user))
        ).order_by('created_at')[:50]

        message_list = []
        for msg in messages:
            message_list.append({
                'id': msg.id,
                'sender_id': msg.sender.id,
                'sender_name': msg.sender.username,
                'content': msg.content,
                'created_at': msg.created_at.strftime('%Y-%m-%d %H:%M'),
                'is_own': msg.sender.id == request.user.id
            })

        return JsonResponse({
            'success': True,
            'messages': message_list
        })

    except User.DoesNotExist:
        return JsonResponse({'success': False, 'message': '用户不存在'})
    except Exception as e:
        print(f"获取消息错误: {str(e)}")
        return JsonResponse({'success': False, 'message': f'获取消息失败: {str(e)}'})


@login_required
@csrf_exempt
def get_message_stats(request):
    """获取消息统计和限制信息"""
    try:
        user_id = request.GET.get('user_id')
        if not user_id:
            return JsonResponse({'success': False, 'message': '用户ID不能为空'})

        other_user = User.objects.get(id=user_id)



        is_following = UserFollow.objects.filter(
            follower=request.user,
            following=other_user
        ).exists()

        is_followed_back = UserFollow.objects.filter(
            follower=other_user,
            following=request.user
        ).exists()

        # 获取已发送消息数量
        sent_messages_count = PrivateMessage.objects.filter(
            sender=request.user,
            receiver=other_user
        ).count()

        # 计算剩余消息数量
        if not is_following:
            remaining_messages = 1 - sent_messages_count
        elif is_following and not is_followed_back:
            remaining_messages = 3 - sent_messages_count
        else:
            remaining_messages = -1  # 无限制

        return JsonResponse({
            'success': True,
            'stats': {
                'is_following': is_following,
                'is_followed_back': is_followed_back,
                'sent_messages_count': sent_messages_count,
                'remaining_messages': remaining_messages,
                'can_send_unlimited': is_followed_back,
                'max_messages': 1 if not is_following else (3 if not is_followed_back else -1)
            }
        })

    except User.DoesNotExist:
        return JsonResponse({'success': False, 'message': '用户不存在'})
    except Exception as e:
        print(f"获取消息统计错误: {str(e)}")
        return JsonResponse({'success': False, 'message': f'获取统计失败: {str(e)}'})

